function changeModelVariableRef(code, model, isAdding, isReset, prevModelVariableRef) {
  if (isReset) {
    this.setState({ modelVariableRef: {} });
    this.nodeRefCountMap = {};
    this.processRefCountMap = {};
    return;
  }
  let codes = code;
  if (!codes.forEach) {
    codes = [code];
  }
  let id;
  let ref;
  let filterKey;
  if (model.id) { // 用户任务
    id = model.id; // eslint-disable-line
    ref = this.nodeRefCountMap;
    filterKey = "id";
  } else if(model.process_id) { // 流程
    id = model.process_id;
    ref = this.processRefCountMap;
    filterKey = "process_id";
  }
  // 由于setState机制问题，连续调用changeModelVariableRef时
  // this.state中的modelVariableRef可能不会即时更新，需要
  // 将上一次调用时更新的modelVariableRef传进来
  let { modelVariableRef } = this.state;
  if (prevModelVariableRef) {
    modelVariableRef = prevModelVariableRef;
  }
  const newVal = { ...modelVariableRef };
  codes.forEach(_code => {
    let item = newVal[_code] || [];
    if (isAdding) {
      if (!ref[id]) {
        item.push(model);
        ref[id] = 0;
      }
      ref[id] += 1;
    } else {
      ref[id] -= 1;
      if (ref[id] <= 0) {
        item = item.filter(i => i[filterKey] !== id);
        delete ref[id];
      }
    }
    newVal[_code] = item;
    if(item.length <= 0) {
      delete newVal[_code];
    }
  })
  this.setState({ modelVariableRef: newVal });
  return newVal;
}
export function setUpRef(instance) {
  // 被引用后流程变量不能删除
  // { varCode: refCount }
  instance.nodeRefCountMap = {} // 用户节点办理人及超时/预警设置中对流程变量的引用计数

  instance.processRefCountMap = {} // 流程高级设置中超时/预警设置中对流程变量的引用计数

  instance.changeModelVariableRef = changeModelVariableRef.bind(instance);

}

export const getCodes = users => users.filter(u => u.type === "VAR").map(u => u.code)

export const extractVarCodesFromTimeoutSetting = timeoutSetting => {
  const { timeoutNotifier: { notifier = [] } = {}, warningSetting = {} } = timeoutSetting || {};
  const { warningRegular: alerts = [] } = warningSetting;
  // 超时设置可能引用了流程变量
  let codes = getCodes(notifier);
  // 预警设置中可能引用了流程变量
  alerts.forEach(alert => {
    const { warningNotifier: { notifier: alertUsers = [] } = {} } = alert;
    codes = codes.concat(getCodes(alertUsers));
  });
  return codes;
}

